package com.example.xss.config.serialize;

import cn.hutool.core.util.ObjectUtil;
import com.example.xss.commom.enums.SensitiveTypeEnum;
import com.example.xss.commom.util.SensitiveUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

/**
 * 脱敏序列化器
 *
 * @author WANGJIET24
 * @date 2021-6-8$
 */
public class SensitiveSerialize extends JsonSerializer<Object> implements ContextualSerializer {

    private SensitiveTypeEnum sensitiveTypeEnum;

    public SensitiveSerialize(SensitiveTypeEnum sensitiveTypeEnum) {
        this.sensitiveTypeEnum = sensitiveTypeEnum;
    }

    public SensitiveSerialize() {
    }

    /**
     * 序列化
     */
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (ObjectUtil.isNull(value)) {
            gen.writeString("");
        }
        switch (sensitiveTypeEnum) {
            case ID_CARD:
                gen.writeString(SensitiveUtils.idCardNum(value.toString()));

            default:
                break;
        }

    }

    /**
     * 筛选序列化器
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty==null) {
            return serializerProvider.findNullValueSerializer(null);
        }
        // 先拿注解
        Sensitive sensitiveInfo = beanProperty.getAnnotation(Sensitive.class);
        if (sensitiveInfo == null) {
            sensitiveInfo = beanProperty.getContextAnnotation(Sensitive.class);
        }
        // 没有注解，就走你
        if (sensitiveInfo == null) {
            // 使用工厂里面其他的方式处理
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        // 类型判断 想法是 特定类型不处理。
        return new SensitiveSerialize(sensitiveInfo.value());
    }
}
